package com.log;

import java.sql.Timestamp;
import java.util.Map;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

import com.PiwikDao;
import com.PiwikPredictionioSysCfg;
import com.PiwikPredictionioSysCfgDao;
import com.PredictionIoService;
import com.google.common.util.concurrent.AbstractExecutionThreadService;

@Component
public class Scanner extends AbstractExecutionThreadService implements HealthIndicator {
	@Autowired
	private PiwikPredictionioSysCfgDao piwikPredictionioSysCfgDao;
	@Autowired
	private PiwikDao piwikdao;
	@Autowired
	private PredictionIoService predictionIoService;
	@Autowired 
	private LogFileService logFileService;
	@Override
	public Health health() {
		return Health.up().withDetail("time_log Scanner", this.state()).build();
	}


	@Override
	protected void run() throws Exception {
		while ( isRunning() ) {
			exec();
		}	
		
	}

	
	 public void exec() {
			PiwikPredictionioSysCfg sysCfg = 
					piwikPredictionioSysCfgDao.
					findOne(PiwikPredictionioSysCfgDao.key_lastQueryPiwikLogLinkVisitActionId);
			
			piwikdao.queryPiwikTime(new Integer(sysCfg.getValue()))
			.forEach( piwikTime->{			
				sysCfg.setValue(piwikTime.get("idlink_va").toString());
				read(piwikTime);
			});
			piwikPredictionioSysCfgDao.save(sysCfg);
	 }


	 void read(Map<String, Object> piwikTime) {
		 Long idlink_va = (Long) piwikTime.get("idlink_va");
		 Timestamp server_time = (Timestamp) piwikTime.get("server_time");		
		 String  frontAppTimeStr   = (String) piwikTime.get("custom_var_v4");
		 PioEventTimeVo eventTime = predictionIoService.getEventTime(idlink_va.toString());
		 DateTime frontAppTime = new DateTime(frontAppTimeStr);
		 Long inPiwikTime = server_time.getTime();
		 Long frontAppToPiwik = inPiwikTime - frontAppTime.getMillis();
		 Long piwikToPio =  eventTime.creationTime.getMillis() - inPiwikTime;

		 String log = idlink_va+" frontAppToPiwik : "+frontAppToPiwik+" ;piwikToPio : "+piwikToPio;
		 logFileService.write(log);
	}




}
